package com.soft.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.soft.dao.TOrderitemDao;
import com.soft.entity.TCart;
import com.soft.entity.TOrder;
import com.soft.entity.TOrderitem;
import com.soft.entity.TUser;
import com.soft.service.TCartService;
import com.soft.service.TOrderService;
import com.soft.service.TOrderitemService;
import com.soft.service.TUserService;
import com.soft.utils.GetDate;
import com.soft.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

import java.util.*;

@Controller

public class UserMainController {
    private TUser login;
    String msg = null;
    @Autowired
    TUserService tUserService;
    @Autowired
    TCartService tCartService;
    @Autowired
    TOrderService tOrderService;
    @Autowired
    TOrderitemService tOrderitemService;

    @RequestMapping({"index", "", "index.html"})
    public String unLoginIndex(Model model, HttpSession session){
        model.addAttribute("cartList", new ArrayList<TCart>());
        model.addAttribute("totalMoney", 0.0f);
        return "user/index-two";
    }

    @RequestMapping("user/register")
    public String register(Model model){
        model.addAttribute("cartList", new ArrayList<TCart>());
        model.addAttribute("totalMoney", 0.0f);
        return "user/register";
    }

    @GetMapping("/user/login")
    public String login(Model model){
        model.addAttribute("cartList", new ArrayList<TCart>());
        model.addAttribute("totalMoney", 0.0f);
        return "user/login";
    }


    //用户登录判断
    @RequestMapping("/user/loginjudge")
    @ResponseBody
    public String judgeLoign(String name, String pwd, Model model, HttpSession session){
//        assert username != null;
        TUser user = new TUser();
        Boolean isExits =  tUserService.queryByNameForBoolean(name);
        if (isExits){
            user = tUserService.queryByName(name);
            if(!user.getPassword().equals(pwd)){
                System.out.println("error!!!!!!");
//                model.addAttribute("msg", "密码错误！");
                return "not";
            }else{//将用户信息加入session
                session.setAttribute("user", user);
                System.out.println("success!!!!!!");
                return "ok";
            }
        }else{
            System.out.println("error!!!!!!!!!!!!!!1");
            return "not";
        }
    }

    /**
     * 登陆成功跳转到首页
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/user/index")
    public String userIndex(Model model, HttpSession session){
        login = (TUser) session.getAttribute("user");
        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(login.getId());//session.getAttribute("user").getId()
        TCartController.cartBar(list, model);
        return "user/index";
    }

    @RequestMapping("main/login")
    public String toLogin(String username, String password, Model model){//, HttpSession session
        return "/user/index";
    }

    @RequestMapping("/user/registerjudge")
    public String  register(String username, String password, Model model, HttpSession session) {

        if (username == null || password == null) {
            model.addAttribute("msg", "请输入用户名，或密码！");
            return "redirect:/register";
        } else if (password.length() < 6 || password.length() > 16) {
            model.addAttribute("msg", "密码格式不正确！（大于6位小于16位）");
            return "redirect:/register";
        } else{
            TUser tUser = new TUser();
            tUser.setUsername(username);
            tUser.setPassword(password);
            Date date = new Date(System.currentTimeMillis());
            tUser.setCreateTime(date);
            tUser.setUpdateTime(date);
            if(tUserService.queryByName(username) != null){
                model.addAttribute("msg", "用户名已被注册！");
                return "redirect:/register";
            } else{
                tUserService.insert(tUser);
                msg = "注册成功！";
                model.addAttribute("msg", "注册成功");
                return "redirect:/user/index";
            }
        }
    }



    @RequestMapping("search")
    public String search(Model model, HttpSession session){
        login = (TUser) session.getAttribute("user");
        model.addAttribute("msg", "ok");
        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(login.getId());//session.getAttribute("user").getId()
        TCartController.cartBar(list, model);
        return "user/page-search";
    }

    @RequestMapping("searchProducts")
    public String searchProducts(String search,Model model, HttpSession session){
        login = (TUser) session.getAttribute("user");
        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(login.getId());//session.getAttribute("user").getId()
        TCartController.cartBar(list, model);
        return "user/page-search";
    }



    @RequestMapping("/checkout")
    public String checkout(Model model, HttpSession session){
        login = (TUser) session.getAttribute("user");
        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(login.getId());//session.getAttribute("user").getId()
        TCartController.cartBar(list, model);
        return "user/checkout";
    }

    @RequestMapping("userCart")
    public String userCart(Model model, HttpSession session){
        login = (TUser) session.getAttribute("user");
        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(login.getId());//session.getAttribute("user").getId()
        TCartController.cartBar(list, model);
        return "user/cart";
    }
//    @RequestMapping("checkout")
//    public String checkout(Model model, HttpSession session){
//        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(4);//session.getAttribute("user").getId()
//        TCartController.cartBar(list, model);
//        return "user/cart";
//    }

    @RequestMapping("userInfo")
    public String userInfo(Model model, HttpSession session){
        login = (TUser) session.getAttribute("user");
        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(login.getId());//session.getAttribute("user").getId()
        TCartController.cartBar(list, model);
        return "user/person";
    }

    @RequestMapping("/pay")
    public String pay(Float totalMoney, Integer orderId, Model model, HttpSession session){
        login = (TUser) session.getAttribute("user");
        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(login.getId());//session.getAttribute("user").getId()
        TCartController.cartBar(list, model);
        model.addAttribute("totalMoney", totalMoney);
        model.addAttribute("orderId", orderId);
        return "user/pay";
    }

    @GetMapping("finishOrder")
//    @ResponseBody
    public String finish(Integer orderId, Model model, HttpSession session){
        Date date = new Date(System.currentTimeMillis());
        TOrder tOrder = new TOrder(); //tOrderService.queryById(orderId);
        tOrder.setPayTime(date);
        tOrder.setUpdateTime(date);
        tOrder.setId(orderId);
        tOrder.setStatus(2);
        //更新订单状态
        tOrderService.update(tOrder);
        //得到订单和订单相关联的物品
        TOrder tOrder1 = tOrderService.getOrderAndOrderItems(orderId);
        model.addAttribute("tOrder", tOrder1);

        model.addAttribute("status", StringUtils.orderStatus(tOrder1.getStatus()));

        login = (TUser) session.getAttribute("user");
        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(login.getId());//session.getAttribute("user").getId()
        TCartController.cartBar(list, model);
        return "/user/finish";
//        return tOrder1;
    }
    @RequestMapping("userOrders")
//    @ResponseBody
    public String userOrders(Integer offset, Integer limit,Model model, HttpSession session){
        login = (TUser) session.getAttribute("user");
        PageInfo<TOrder> pageInfo = tOrderService.getUserOrdersAndOrderItems(offset, limit, login.getId());//session
        model.addAttribute("pageInfo", pageInfo);


        login = (TUser) session.getAttribute("user");
        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(login.getId());//session.getAttribute("user").getId()
        TCartController.cartBar(list, model);
        return "/user/orders";
//        return pageInfo;
    }
    //博客
    @GetMapping("/blog")
    public String blog(Model model, HttpSession session){

        login = (TUser) session.getAttribute("user");
        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(login.getId());//session.getAttribute("user").getId()
        TCartController.cartBar(list, model);
        return "/user/blog";
    }
    //关于我们
    @GetMapping("about-us")
    public String about_us(Model model, HttpSession session){

        login = (TUser) session.getAttribute("user");
        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(login.getId());//session.getAttribute("user").getId()
        TCartController.cartBar(list, model);
        return "/user/about-us";
    }
    //联系我们
    @GetMapping("/contact")
    public String contact(Model model, HttpSession session){
        login = (TUser) session.getAttribute("user");
        List<TCart> list = tCartService.findAllCartAssociateProductByUserId(login.getId());//session.getAttribute("user").getId()
        TCartController.cartBar(list, model);
        return "/user/contact";
    }
}
